﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PanasonicWarranty.Business;
using PanasonicWarranty.UI;
using System.Web.Security;

namespace PanasonicWarranty.UI
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[SESSION.USER_NAME] == null)
            {
                lbtnCurUser.Visible = lbtnLogout.Visible = false;
            }
            else
            {
                lbtnCurUser.Visible = lbtnLogout.Visible = true;
                lbtnCurUser.Text = ((pepsi_User)Session[SESSION.USER_NAME]).Name;
            }
            if (!IsPostBack)
            {
                if (Session[SESSION.USER_NAME] == null) return;
                using (var context = new PanasonicWarrantyDBDataContext(LocalSetting.ConnectionString))
                {
                    pepsi_User logUser = (pepsi_User)Session[SESSION.USER_NAME];
                    var func = context.pepsi_Functions
                        .Where(p => context.pepsi_Function_Roles.Any(fr =>
                                        p.FunctionID == fr.FunctionID
                                        && context.pepsi_Roles.Any(r => r.RoleId == fr.RoleID
                                            && context.pepsi_User_Roles.Any(ur => ur.RoleID == r.RoleId
                                                && ur.UserID == logUser.UserID))))
                        .OrderBy(p => p.OrderID);
                    foreach (var item in func)
                    {
                        NavigationMenu.Items.Add(new MenuItem(item.DisplayText, item.FunctionID.ToString(), "", item.Url));
                    }
                }
            }
        }

        protected void lbtnLogout_Click(object sender, EventArgs e)
        {
            Session.Clear();
            Session.Add(SESSION.RETURN_URL, Request.RawUrl);
            Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["LoginURL"]);
        }

        protected void lbtnCurUser_Click(object sender, EventArgs e)
        {
            Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["ChangePasswordURL"]);
        }
    }
}
